<template>
  <el-dialog
      v-model="visible"
      :title="mode === 'add' ? '新增角色' : '编辑角色'"
      width="600px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="right"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
      </el-form-item>

      <el-form-item label="角色编码" prop="roleKey">
        <el-input v-model="formData.roleKey" placeholder="请输入角色编码" />
      </el-form-item>

      <el-form-item label="排序" prop="roleSort">
        <el-input-number
            v-model="formData.roleSort"
            :min="0"
            :max="999"
            controls-position="right"
        />
      </el-form-item>

      <el-form-item label="数据范围" prop="dataScope">
        <el-select v-model="formData.dataScope" placeholder="请选择数据范围">
          <el-option label="全部数据" value="1" />
          <el-option label="自定义数据" value="2" />
          <el-option label="本部门数据" value="3" />
          <el-option label="本部门及以下数据" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio label="0">启用</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { saveRole, updateRole } from '@/api/role'

const props = defineProps({
  modelValue: Boolean,
  roleData: Object,
  mode: String
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref()

const formData = reactive({
  roleName: '',
  roleKey: '',
  roleSort: 0,
  dataScope: '1',
  status: '0',
  remark: ''
})

const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 30, message: '角色名称长度在2-30个字符', trigger: 'blur' }
  ],
  // roleKey: [
  //   { required: true, message: '请输入角色编码', trigger: 'blur' },
  //   { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  // ],
  roleSort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  dataScope: [
    { required: true, message: '请选择数据范围', trigger: 'change' }
  ]
}

// 处理对话框显示
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    if (props.mode === 'edit' && props.roleData) {
      Object.assign(formData, props.roleData)
    } else {
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    roleName: '',
    roleKey: '',
    roleSort: 0,
    dataScope: '1',
    status: '0',
    remark: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  loading.value = true
  try {
    if (props.mode === 'add') {
      await saveRole(formData)
      ElMessage.success('新增成功')
    } else {
      await updateRole(formData)
      ElMessage.success('更新成功')
    }
    emit('success')
    visible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}
</script>
